﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using VIA.Integration;
using VIA.Integration.LeadShine;
using VIA.SiMoJi.Domain.Electronics;

namespace VIA.SiMoJi.Domain.Inspection
{
    public static class Functions
    {

        public static List<T> SelectObjects<T>(List<T> objs, List<bool> bools)
        {
            if (objs?.Count != bools?.Count) throw new Exception("操作数量不一致");
            List<T> selected = new();
            for (int i = 0; i < objs.Count; i++)
            {
                if (bools[i])
                    selected.Add(objs[i]);
            }
            return selected;
        }

        /// <summary>
        /// 同时移动多个轴
        /// </summary>
        /// <param name="position"></param>
        /// <param name="axisLs"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static async Task MoveAxis(IEnumerable<IServoAxis> axisLs, string position, CancellationToken cancelToken = default)
        {
            await Parallel.ForEachAsync(axisLs, cancelToken, async (x, c) => await x.MoveToAsync(position, cancelToken));
        }

        /// <summary>
        /// 检测多个轴是否在位置
        /// </summary>
        /// <returns></returns>
        public static bool CheckIsAxisInPosition(IEnumerable<IServoAxis> axises, string name)
        {
            return axises.Cast<DmcAxis>().All(x => x.CheckIsInPosition(name));
        }

        public static bool GetValueFromUint(CardIoPoint point, uint data)
        {
            var bit = point.PortNo % 32;
            uint dd = (uint)1 << bit;
            uint value = data & dd;
            return value == 0;
        }

        public static T GetRecord<T>(string name) where T : new()
        {
            try
            {
                string path = Path.Combine(Environment.CurrentDirectory, "RunningRecord", name);
                path = Path.ChangeExtension(path, ".json");
                if (!File.Exists(path))
                {
                    var file = File.Create(path);
                    //file.Dispose();
                }
                using StreamReader sw = new StreamReader(path);
                var str = sw.ReadToEnd();
                T record = JsonConvert.DeserializeObject<T>(str);
                record ??= new T() { };
                return record;

            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }
}
